<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '需求信息' },
          { name: 'box-dtl', title: '需求明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <div id="box-base" class="box-title">需求信息</div>
          <customFormItem
            label="科室"
            name="deptName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.dept(deptIdChange)"
          />
          <customFormItem label="计划类型" name="demandType" :parent="_self" :form="form"
                          :type="constCommon.formItemType.selectDict.name"
                          :config="{dictType: constCommon.dictType.demandType}"
          />
          <customFormItem
            label="需求到货日期"
            name="dateLates"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
          />
          <customFormItem
            label="需求单号"
            name="busKey"
            :parent="_self"
            :form="form"
            disabled
            :config="{defaultValue: '自动获取'}"
          />
          <customFormItem
            label="需求日期"
            name="busDate"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.datePicker.name"
            disabled
          />
          <customFormItem
            label="需求人"
            name="busUser"
            :parent="_self"
            :form="form"
            disabled
          />
          <customFormItem
            label="申请仓库"
            name="applyWarehouseName"
            :parent="_self"
            :form="form"
            disabled
          />
          <customFormItem
            label="金额"
            name="amount"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.inputNumber.name"
            :config="{defaultValue: 0}"
            disabled
          />
          <customFormItem
            label="备注"
            name="remark"
            :parent="_self"
            :form="form"
          />

        </template>
      </customForm>

      <div id="box-dtl" class="box-title">需求明细</div>
      <data-view
        propViewKey="dept_demand_item"
        :propInitData="form"
        ref="childDataView"
        :propParentPage="_self"
        :propAutoFetchData="false"
        :propsDisableDbClick="true"
        :propHideFlowSelect="true"
        @edit-input="editInput"
        :propFlowKey="propParent.propFlowKey"
        @extra-button-click="handleExtraButton"
        @customSelectFocus="customSelectFocus"
        @afterTableDataChange="afterTableDataChange"
      >
      </data-view>
    </div>
  </div>

</template>
<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'
export default {
  data() {
    return {
      form: {},
      viewData: {},
    }
  },
  components: {
    customAnchor
  }
  ,
  created() {
    let that = this
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        this.$set(this.form, 'demandType', this.form.demandType)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (this.propStatus == 'addnew') {
          this.$set(this.form, 'busUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'busDate', new Date().format(this.dates.defaultDatePattern))
          this.$set(this.form, 'deptId', this.utils.getCurrentUser().deptId)
          this.$set(this.form, 'deptName', this.utils.getCurrentUser().deptName)
          this.$set(this.form, 'dateLates', this.dates.getDateAfterDays(3))
          this.$set(this.form, 'demandType', 'normal')
          this.$set(this.form, 'applyWarehouseId', this.utils.getCurrentWarehouse().warehouseId)
          this.$set(this.form, 'applyWarehouseName', this.utils.getCurrentWarehouse().warehouseName)
        }
        this.loadDtl()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {},
      beforeFlow: (flowButtonKey) => {
        if (that.form.countDtl == 0) {
          this.utilMessage.error('需求明细为空，不允许提交')
          return false
        }
        return true
      },
      afterFlow: (valueTo) => {
      },
      beforeClose: () => {
        return true
      },
      async afterClick(button, data, viewForm) {
        let {key: buttonKey} = button
        if (buttonKey == 'cp_ref_orders') { //查看关联订单
          let orderIds = that.$refs.childDataView.getRows0()
            .map(item => item.orderId)
          global.utils.openMenu('purchase/order/index', {id: orderIds})
        }
        if (buttonKey == 'preview') {
          // let param = await global.printSet.getPrintParams(viewForm, 'demand')

          let param = {
            that: that, 				//当前调用对象
            configList: [  						//打印配置，可以多个
              {
                //打印配置
                printBusType:  'demand', 			//打印业务类型，来源print_template.bus_type，同constPrint.busKey
                //主单据数据或者数据查询配置
                formData:  that.form,				//数据对象
                formDataId: that.form.id,
              }
            ]
          }
          global.utilPrint.openFormPrint(param)
        }
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: String
  },
  methods: {
    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'packageQty') {
        this.$set(row, 'skuQty', this.utilNum.toFixed(row.packageRate * row.packageQty))
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },
    //按钮事件
    async handleExtraButton(para) {
      switch(para.button.key) {
        case 'chosePackage': //选择需求计划模板
          this.utilSelect.matrPackTempletMore(this.matrSelect, this.form.deptId, this.constCommon.dictType.tempTypeDemand)
          break
      }
    },

    // 自定义选择聚焦回调
    customSelectFocus(column, row) {
      // 选择商品
      if (column.name == 'matrName') {
        this.utilSelect.matrMoreForDept(this.matrSelect,
          this.form.deptId, this.form.warehouseId,
          'dept_demand_item', 'demand_id', this.form.id,
          null,
          this.constCommon.dictType.deptBusTypeDemand
        )
      }
      // 包装名称
      if (column.name == 'packageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId, null, true)
      }
    },
    // 商品选择后
    matrSelect(rows, refName) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this.saveBatchItem(rows, true)
        })
        return
      }
      this.saveBatchItem(rows, true)
    },
    // 批量保存明细
    saveBatchItem(rows, isLoadForm) {
      this.utilVue.loadShow(true)
      let rowsSave = []
      for (let i = 0; i < rows.length; i++) {
        if (rows[i].childData && rows[i].childData.length > 0) {
          let childCheckedList = rows[i].childData.filter(ob => ob.checked && ob.checked == true)
          //如果子表格没有任何选中，但是因为主数据选中了，就添加所有的
          if (childCheckedList == null || childCheckedList.length < 1) childCheckedList = rows[i].childData
          if (childCheckedList != null) {
            let matrIdList = []
            childCheckedList.forEach(ob => {
              let rowsSaveChild = {
                demandId: this.form.id,
                packTempletMatrId: ob.matrId,
                packTempletId: ob.packTempletId,
                packTempletItemId: ob.id,
              }
              rowsSave.push(rowsSaveChild)
            })
          }
          continue
        }
        rows[i].demandId = this.form.id
        rowsSave.push(rows[i])
      }
      this.$ajax.post('/dept/demandItem/saveBatchForPurchaseDemand', rowsSave).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.form.countDtl = rows.length
          if (isLoadForm) {
            this.afterTableDataChange()
          }
        }
      })
    },
    // 单位选择后
    packageUnitSelect(row, refName) {
      // 当前选中行
      let currentRow = this.$refs.childDataView.getCurrentRow()
      //换算单位后是否为整数
      if (this.utilNum.isInt(currentRow.skuQty / row.rate)) {
        this.$set(currentRow, 'packageUnit', row.unit)
        this.$set(currentRow, 'packageRate', row.rate)
        this.$set(currentRow, 'packageQty', currentRow.skuQty / row.rate)
        this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
      } else  {
        this.utilMessage.warning('所选择包装换算后不是整数，包装数量已经置为1')
        this.$set(currentRow, 'packageUnit', row.unit)
        this.$set(currentRow, 'packageRate', row.rate)
        this.$set(currentRow, 'packageQty', 1)
        this.$set(currentRow, 'amount', currentRow.skuPrice * currentRow.skuQty)
      }
    },

    // 加载明细
    loadDtl() {
      let wrapper = this.$newWrapper()
      if (this.form.id) {
        wrapper.eq('demandId', this.form.id)
      } else {
        wrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(wrapper)
    },

    // 明细 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },

    // 科室选择
    deptIdChange(item) {
      this.$set(this.form, 'deptId', item.id)
      this.$set(this.form, 'deptName', item.name)
    }

    //刷新左侧单元格
    // fetchDataLeft() {
    //   let userParam = {
    //     warehouseId: this.utils.getCurrentWarehouse().id ? this.utils.getCurrentWarehouse().id : -1,
    //     deptId: this.utils.getCurrentUser().deptId
    //   }
    //   this.$refs.wm_stock_applydemand.setUserParam(userParam)
    //
    //   this.$refs.wm_stock_applydemand.fetchData()
    // },
  }
}
</script>
<style lang="scss" scoped>
</style>
